<?php

function hierarchyListFolderData($mes) {
  global $_GET, $path, $style, $session_id, $data, $term_Thing_ID, $language, $header;
  $filename = $path[$style]["tpl"]."/attrdata.xml";
  $fp = fopen($filename, "r");
  $contents = fread($fp, filesize ($filename));
  fclose ($fp);

  preg_match("/\%REPEAT\%(.*?)\%REPEAT\%/s", $contents, $matches);
  preg_match("/\%REPDAT\%(.*?)\%REPDAT\%/s", $matches[1], $datmatches);

  $udata = str_replace($datmatches[0], "", $matches[1]);
  $udata = str_replace("%GROUP_ID%", "0", $udata);
  $udata = str_replace("%GROUP_TL%", $mes, $udata);
  $contents = str_replace("%DatHref%", "index.php?trg=ontoedit&amp;act=hierarchylistdata&amp;sid=".
              $session_id."&amp;uid=".$_GET["uid"], $contents);

  header ($header["xml"]);
  return str_replace($matches[0], $udata, $contents);
}

function getHierarchy($class_id, $matches, $session_id){
  global $_GET, $undef_id, $language;

  $next_class_id = $class_id;
  $sql_str = "SELECT t.text FROM class c, term t WHERE t.id=c.term_id and c.id=".$class_id;
  getData($sql_str, $next_data);
  $inherited = false;
  $rep_cont = "";
  while ($next_data["text"] != "Thing"){
    $sql_str = "SELECT * FROM hierarchy h, term t, class c WHERE c.term_id = t.id and t.lang_id = ".$language["content"]." and ((h.child_class_id = c.id and h.parent_class_id = ".$next_class_id.") or (h.parent_class_id = c.id and h.child_class_id = ".$next_class_id."))";
    $i_max = getMultData($sql_str, $ontosdata);

    $sql_str = "SELECT * FROM hierarchy h, term t WHERE t.id=".$undef_id." and h.child_class_id=-1 and h.parent_class_id=".$next_class_id;
    if (getData($sql_str, $ontosdata1) == 1){
      $ontosdata[$i_max]["parent_class_id"] = $next_class_id;
      $ontosdata[$i_max]["child_class_id"] = $ontosdata1["child_class_id"];
      $ontosdata[$i_max]["text"] = $ontosdata1["text"];
      $i_max++;
    };

    for ($i = 0; $i < $i_max; $i++) {
      if ($ontosdata[$i]["parent_class_id"] == $next_class_id){
        // simple hierarhical
        if ($inherited){
          $tmp_attr = str_replace("%CLASS_ID%", "h".$class_id."h".$ontosdata[$i]["child_class_id"], $matches[1]);
          $tmp_attr = str_replace("%CLASS_LN%", "index.php?trg=ontoedit&amp;act=hierarchydata&amp;sid=".$session_id."&amp;uid="."h".$class_id."h".$ontosdata[$i]["child_class_id"], $tmp_attr);
          $tmp_attr = str_replace("%CHILD_LN%", "index.php?trg=ontoedit&amp;act=hierarchyfunctional&amp;sid=".$session_id."&amp;uid="."h".$class_id."h".$ontosdata[$i]["child_class_id"], $tmp_attr);
          $tmp_attr = str_replace("%IMG_TYPE%", "inhattr", $tmp_attr);
        }else{
          $tmp_attr = str_replace("%CLASS_ID%", "h".$ontosdata[$i]["parent_class_id"]."h".$ontosdata[$i]["child_class_id"], $matches[1]);
          $tmp_attr = str_replace("%CLASS_LN%", "index.php?trg=ontoedit&amp;act=hierarchydata&amp;sid=".$session_id."&amp;uid="."h".$ontosdata[$i]["parent_class_id"]."h".$ontosdata[$i]["child_class_id"], $tmp_attr);
          $tmp_attr = str_replace("%CHILD_LN%", "index.php?trg=ontoedit&amp;act=hierarchyfunctional&amp;sid=".$session_id."&amp;uid="."h".$ontosdata[$i]["parent_class_id"]."h".$ontosdata[$i]["child_class_id"], $tmp_attr);
          $tmp_attr = str_replace("%IMG_TYPE%", "attr", $tmp_attr);
        };
      }else{
        // revers hierarhical
        if ($inherited){
          $tmp_attr = str_replace("%CLASS_ID%", "h".$class_id."h".$ontosdata[$i]["parent_class_id"], $matches[1]);
          $tmp_attr = str_replace("%CLASS_LN%", "index.php?trg=ontoedit&amp;act=hierarchydata&amp;sid=".$session_id."&amp;uid="."h".$class_id."h".$ontosdata[$i]["parent_class_id"], $tmp_attr);
          $tmp_attr = str_replace("%CHILD_LN%", "index.php?trg=ontoedit&amp;act=hierarchyfunctional&amp;sid=".$session_id."&amp;uid="."h".$class_id."h".$ontosdata[$i]["parent_class_id"], $tmp_attr);
          $tmp_attr = str_replace("%IMG_TYPE%", "inhattr", $tmp_attr);
        }else{
          $tmp_attr = str_replace("%CLASS_ID%", "h".$ontosdata[$i]["child_class_id"]."h".$ontosdata[$i]["parent_class_id"], $matches[1]);
          $tmp_attr = str_replace("%CLASS_LN%", "index.php?trg=ontoedit&amp;act=hierarchydata&amp;sid=".$session_id."&amp;uid="."h".$ontosdata[$i]["child_class_id"]."h".$ontosdata[$i]["parent_class_id"], $tmp_attr);
          $tmp_attr = str_replace("%CHILD_LN%", "index.php?trg=ontoedit&amp;act=hierarchyfunctional&amp;sid=".$session_id."&amp;uid="."h".$ontosdata[$i]["child_class_id"]."h".$ontosdata[$i]["parent_class_id"], $tmp_attr);
          $tmp_attr = str_replace("%IMG_TYPE%", "hierarhical_reverce", $tmp_attr);
        };
      };

      if (isset($_GET["sel"]) && $_GET["sel"] == "h".$ontosdata[$i]["parent_class_id"]."h".$ontosdata[$i]["child_class_id"])
        $tmp_attr = str_replace("%ACT%", "select", $tmp_attr);

      $tmp_attr = str_replace("%CLASS_NM%", $ontosdata[$i]["text"], $tmp_attr);
      if ($inherited)
        $tmp_attr = str_replace("%IMG_TYPE%", "inhattr", $tmp_attr);
      else
        $tmp_attr = str_replace("%IMG_TYPE%", "attr", $tmp_attr);

      $rep_cont .= $tmp_attr;
    };
    $sql_str = "SELECT parent_id FROM class WHERE id=".$next_class_id;
    getData($sql_str, $next_data);
    $next_class_id = $next_data["parent_id"];
    $sql_str = "SELECT t.text FROM class c, term t WHERE t.id=c.term_id and c.id=".$next_class_id;
    getData($sql_str, $next_data);
    $inherited = true;
  };
  return $rep_cont;
};


function hierarchyList(){
 global $_GET, $data, $path, $style, $session_id, $language, $header;
  $filename = $path[$style]["tpl"]."/classes.xml";
  $fp = fopen($filename, "r");
  $contents = fread($fp, filesize ($filename));
  fclose ($fp);

  preg_match("/\%REPEAT\%(.*?)\%REPEAT\%/s", $contents, $matches);
  $rep_cont = getHierarchy(str_replace("h","",$_GET["uid"]), $matches, $session_id);
  $contents = str_replace($matches[0], $rep_cont, $contents);
  header ($header["xml"]);
  return $contents;
};


function my_h_sort($childs){
  for ($i = 0; $i < count($childs) - 1; $i++){
    for ($j = 0; $j < count($childs) - 1; $j++){
      if (strcmp($childs[$j]["text"], $childs[$j + 1]["text"]) > 0){
        $time = $childs[$j]["text"];
        $childs[$j]["text"] = $childs[$j + 1]["text"];
        $childs[$j + 1]["text"] = $time;

        $time = $childs[$j]["id"];
        $childs[$j]["id"] = $childs[$j + 1]["id"];
        $childs[$j + 1]["id"] = $time;
      };
    };
  };
  return $childs;
};

function hierarchy_functional(){
  global $_GET, $data, $path, $style, $session_id, $language, $header;

  include_once "functional.php";

  $filename = $path[$style]["tpl"]."/classes.xml";
  $fp = fopen($filename, "r");
  $contents = fread($fp, filesize ($filename));
  fclose ($fp);
  preg_match("/\%REPEAT\%(.*?)\%REPEAT\%/s", $contents, $matches);
  $classid = substr($_GET["uid"], 1, strpos(substr($_GET["uid"], 1), "h"));
  $childclassid = substr($_GET["uid"], strpos(substr($_GET["uid"], 1), "h") + 2);

  // functional constraints
  $tmp_attr = str_replace("%CLASS_ID%", "funhlist".$classid."h".$childclassid, $matches[1]);
  $tmp_attr = str_replace("%CLASS_NM%", getMessage("Functional constraints"), $tmp_attr);
  $tmp_attr = str_replace("%IMG_TYPE%", "folder", $tmp_attr);
  $tmp_attr = str_replace("%CLASS_LN%", "index.php?trg=ontoedit&amp;act=functionallistdata&amp;sid=".$session_id."&amp;uid=funhlist".$classid."h".$childclassid, $tmp_attr);

  if (getFunctional($classid, $matches, $session_id, "hierarchy") != "")
    $tmp_attr = str_replace("%CHILD_LN%", "index.php?trg=ontoedit&amp;act=functionallist&amp;sid=".$session_id."&amp;uid=funhlist".$classid."h".$childclassid, $tmp_attr);
  else
    $tmp_attr = str_replace("%CHILD_LN%", "", $tmp_attr);
  $rep_cont .= $tmp_attr;
  // end FC
  $contents = str_replace($matches[0], $rep_cont, $contents);
  header ($header["xml"]);
  return $contents;
};

function get_h_child($parent, $bad_child, &$childs, &$count_childs, $ID){
  global $language;
  $i_max = getMultData("SELECT t.text, c.id FROM class c, term t ".
              "WHERE c.term_id=t.id and t.lang_id = ".$language["content"]." and c.parent_id=".$parent." and c.id<>".$bad_child, $related_class);
  for ($i = 0; $i < $i_max; $i++){
    //if ((getdata("SELECT * FROM hierarchy WHERE parent_class_id=".$ID." and child_class_id=".$related_class[$i]["id"], $data) != 1)&&
      // (getdata("SELECT * FROM hierarchy WHERE child_class_id=".$ID." and parent_class_id=".$related_class[$i]["id"], $data) != 1)){
      $childs[$count_childs]["id"] = $related_class[$i]["id"];
      $childs[$count_childs]["text"] = $related_class[$i]["text"];
      $count_childs++;
    //};
    get_h_child($related_class[$i]["id"], 0, $childs, $count_childs, $ID);
  };
};

function get_h_related_class(&$childs, $ID){
  getData("SELECT parent_id FROM class ".
          "WHERE id=".$ID, $related_class);
  $childs = Array();$count_childs = 0;
  if ($ID != "Thing")
    get_h_child($related_class["parent_id"], $ID, $childs, $count_childs, $ID);
  getData("SELECT t.text FROM class c, term t ".
          "WHERE c.term_id=t.id and c.id=".$related_class["parent_id"], $name_of_class);
  while ($name_of_class["text"] != "Thing"){
    $bad_class = $related_class["parent_id"];
    getData("SELECT c.parent_id, t.text FROM class c, term t ".
            "WHERE c.term_id=t.id and c.id=".$related_class["parent_id"], $related_class);
    get_h_child($related_class["parent_id"], $bad_class, $childs, $count_childs, $ID);
    getData("SELECT t.text FROM class c, term t ".
            "WHERE c.term_id=t.id and c.id=".$related_class["parent_id"], $name_of_class);
  };
  $childs = my_h_sort($childs);
};

function hierarchyData($new_id, $new_cardmin, $new_cardmax) {
  global $_GET, $path, $style, $session_id, $data, $term_Thing_ID, $language, $header;
  $filename = $path[$style]["tpl"]."/attrdata.xml";
  $fp = fopen($filename, "r");
  $contents = fread($fp, filesize ($filename));
  fclose ($fp);

  preg_match("/\%REPEAT\%(.*?)\%REPEAT\%/s", $contents, $matches);
  preg_match("/\%REPDAT\%(.*?)\%REPDAT\%/s", $matches[1], $datmatches);
  preg_match("/\%REPOPT\%(.*?)\%REPOPT\%/s", $datmatches[1], $optmatches);
  $rep_cont = "";
  $ID[0] = substr($_GET["uid"], strpos($_GET["uid"], "h") + 1,strrpos($_GET["uid"], "h") - strpos($_GET["uid"], "h") - 1);
  $ID[1] = substr($_GET["uid"], strrpos($_GET["uid"], "h") + 1);

  if ($new_id > -1){
    $ID[1] = $new_id;
    $_GET["uid"] = "h".$ID[0]."h".$ID[1];
  };

  getData("SELECT * FROM term t, class c WHERE c.term_id=t.id and c.id=".$ID[0], $class_name);
  $class_name["text"] = htmlspecialchars($class_name["text"]);

  getData("SELECT * FROM term t, class c WHERE c.term_id=t.id and c.id=".$ID[1], $class_name1);
  $class_name1["text"] = htmlspecialchars($class_name1["text"]);

  getData("SELECT * FROM term t, class c, ontology o WHERE c.onto_id=o.id and o.term_id=t.id and c.id=".$ID[0], $onto_name);
  $onto_name["text"] = htmlspecialchars($onto_name["text"]);

  getData("SELECT * FROM hierarchy WHERE (parent_class_id=".$ID[0]." and child_class_id=".$ID[1].") or (child_class_id=".$ID[0]." and parent_class_id=".$ID[1].")", $cardinality);

  if ($new_cardmin>-1){
    $cardinality["card_min"] = $new_cardmin;
    $cardinality["card_max"] = $new_cardmax;
  };

    $childs1 = Array();$childs = Array();
  if ($ID[1] == -1){
    get_h_related_class($childs1, $ID[0]);

    $childs_h = Array(); $count = 0;
    hierarchy_child($ID[0], $childs_h, $count);
    $k = 0;
    for ($i = 0; $i < count($childs1); $i++){
      $b = true;
      for ($j = 0; $j < count($childs_h); $j++){
        if ($childs1[$i]["id"] == $childs_h[$j]["id"])
          $b = false;
      };
      if ($b){
          $childs[$k] = $childs1[$i];
          $k++;
        };
    };
    $childs1 = $childs;

    $inh_h = Array(); $childs = Array();
    $count = 0;$k = 0;
    get_h_inherited($ID[0], $inh_h, $count);
    for ($i = 0; $i < count($childs1); $i++){
      $b = true;
      for ($j = 0; $j < count($inh_h); $j++){
        if ($childs1[$i]["id"] == $inh_h[$j])
          $b = false;
      };
      if ($b){
          $childs[$k] = $childs1[$i];
          $k++;
        };

    };
    if (count($inh_h) == 0)
      $childs = $childs1;

    //Test of acons
    include "acon.php";
    $childs1 = $childs;
    $inh_acon = Array();$childs = Array();
    $count = 0;$k = 0;
    get_acon_inherited($ID[0], $inh_acon, $count);
    for ($i = 0; $i < count($childs1); $i++){
      $b = true;
      for ($j = 0; $j < count($inh_acon); $j++){
        if ($childs1[$i]["id"] == $inh_acon[$j])
          $b = false;
      };
      if ($b){
          $childs[$k] = $childs1[$i];
          $k++;
        };

    };
    if (count($inh_acon) == 0)
      $childs = $childs1;
  };

  $udata = "";
  if ($data["type"] >= 1) { //user
    //New name
    if ($new_id > -1){
      $contents = str_replace("%NAME%", $class_name1["text"], $contents);
      $contents = str_replace("%ID%", $_GET["uid"], $contents);
      $contents = str_replace("%DatHref%", "index.php?trg=ontoedit&amp;act=hierarchydata&amp;sid=".
                  $session_id."&amp;uid=".$_GET["uid"], $contents);
    };

    //Class Name
    $classlb = str_replace($optmatches[0], "", $datmatches[1]);
    $classlb = str_replace("%TYPE%", "Label", $classlb);
    $classlb = str_replace("%NODE_ID%", "cname", $classlb);
    $classlb = str_replace("%NODE_TL%", getMessage("Class Name"), $classlb);
    $classlb = str_replace("%VALUE%", $class_name["text"], $classlb);
    //Ontology Name
    $iclasslb = str_replace($optmatches[0], "", $datmatches[1]);
    $iclasslb = str_replace("%TYPE%", "Label", $iclasslb);
    $iclasslb = str_replace("%NODE_ID%", "oname", $iclasslb);
    $iclasslb = str_replace("%NODE_TL%", getMessage("Ontology Name"), $iclasslb);
    $iclasslb = str_replace("%VALUE%", $onto_name["text"], $iclasslb);

    $iparclasslb = str_replace($optmatches[0], "", $datmatches[1]);
    $iparclasslb = str_replace("%TYPE%", "Hidden", $iparclasslb);
    $iparclasslb = str_replace("%NODE_ID%", "ohidd", $iparclasslb);
    $iparclasslb = str_replace("%NODE_TL%", "", $iparclasslb);
    $iparclasslb = str_replace("%VALUE%", $ID[0], $iparclasslb);

    $ichiclasslb = str_replace($optmatches[0], "", $datmatches[1]);
    $ichiclasslb = str_replace("%TYPE%", "Hidden", $ichiclasslb);
    $ichiclasslb = str_replace("%NODE_ID%", "ohidd2", $ichiclasslb);
    $ichiclasslb = str_replace("%NODE_TL%", "", $ichiclasslb);
    $ichiclasslb = str_replace("%VALUE%", $ID[1], $ichiclasslb);

    if (getMultData("SELECT * FROM hierarchy WHERE parent_class_id =".$ID[0]." and child_class_id = ".$ID[1], $test_hierarchy) == 1){

       $cardinmin = str_replace($optmatches[0], "", $datmatches[1]);
       $cardinmin = str_replace("%TYPE%", "Text", $cardinmin);
       $cardinmin = str_replace("%NODE_ID%", "ocardmin", $cardinmin);
       $cardinmin = str_replace("%NODE_TL%", getMessage("cardinality min"), $cardinmin);
       $cardinmin = str_replace("%VALUE%", $cardinality["card_min"], $cardinmin);

       // echo name of the constraint
       $cardinmax = str_replace($optmatches[0], "", $datmatches[1]);
       $cardinmax = str_replace("%TYPE%", "Text", $cardinmax);
       $cardinmax = str_replace("%NODE_ID%", "ocardmax", $cardinmax);
       $cardinmax = str_replace("%NODE_TL%", getMessage("cardinality max"), $cardinmax);
       $cardinmax = str_replace("%VALUE%", $cardinality["card_max"], $cardinmax);

       getData("SELECT t.text FROM term t, hierarchy h "."WHERE h.constr_name = t.id and t.lang_id = ".$language["content"]." and ((h.parent_class_id = ".$ID[0]." and h.child_class_id = ".$ID[1].") or (h.child_class_id = ".$ID[0]." and h.parent_class_id = ".$ID[1]."))", $constr_info);

       $constr_name = str_replace($optmatches[0], "", $datmatches[1]);
       $constr_name = str_replace("%TYPE%", "Text", $constr_name);
       $constr_name = str_replace("%NODE_ID%", "oconstrname", $constr_name);
       $constr_name = str_replace("%NODE_TL%", getMessage("Relationship Name"), $constr_name);
       $constr_name = str_replace("%VALUE%", $constr_info["text"], $constr_name);

       if ((getdata("SELECT * FROM hierarchy WHERE (parent_class_id=".$ID[0]." and child_class_id=".$ID[1].") or (child_class_id=".$ID[0]." and parent_class_id=".$ID[1].")", $onto_data) == 1)&&(count($childs) > 0)&&($ID[1]==-1)){
         $opts = "";
         for ($i = 0; $i < count($childs); $i++) {
           $childs[$i]["text"] = htmlspecialchars($childs[$i]["text"]);
           $opt = str_replace("%OPT_ID%", $childs[$i]["id"], $optmatches[1]);
           $opt = str_replace("%OPT_TL%", $childs[$i]["text"], $opt);
           if ($childs[$i]["id"] == $ID[1])
             $opt = str_replace("%SELECTED%", "selected", $opt);
           else
             $opt = str_replace("%SELECTED%", "0", $opt);
           $opts .= $opt;
         }
         //domain
         $utype = str_replace($optmatches[0], $opts, $datmatches[1]);
         $utype = str_replace("%TYPE%", "Option", $utype);
         $utype = str_replace("%NODE_ID%", "otype", $utype);
         $utype = str_replace("%NODE_TL%", getMessage("Related Class"), $utype);

         $ubutn = str_replace($optmatches[0], "", $datmatches[1]);
         $ubutn = str_replace("%TYPE%", "Button", $ubutn);
         $ubutn = str_replace("%NODE_ID%", "obutn", $ubutn);
         $ubutn = str_replace("%NODE_TL%", getMessage("Save"), $ubutn);
         $ubutn = str_replace("%VALUE%", "'0','otype','ohidd','ohidd2', 'ocardmin', 'ocardmax'", $ubutn);
       }else{
         $utype = "";
         $ubutn = str_replace($optmatches[0], "", $datmatches[1]);
         $ubutn = str_replace("%TYPE%", "Button", $ubutn);
         $ubutn = str_replace("%NODE_ID%", "obutn", $ubutn);
         $ubutn = str_replace("%NODE_TL%", getMessage("Save"), $ubutn);
         $ubutn = str_replace("%VALUE%", "'0', 'iaid', 'ohidd','ohidd2','ocardmin', 'ocardmax', 'oconstrname'", $ubutn);
       };

                $sql = "SELECT o.type_id FROM class as c INNER JOIN ontology as o ON (o.id = c.base_onto_id) WHERE c.id = ".$ID[0];
                getData($sql, $class);
                $hcid = "";
                include "controls.php";
                $grp1 = new ControlGroup(1, getMessage("Input Attribute"), $matches[1], $datmatches, $optmatches);

                $tc_id = $grp1->addControl("Hidden", "iaid", "", "0");
                $hcid = $grp1->getControl($tc_id);

                if ($class['type_id'] == 2 && $ID[1] > 0) {
                        $sql = "SELECT o.type_id FROM class as c INNER JOIN ontology as o ON (o.id = c.base_onto_id) WHERE c.id = ".$ID[1];
                        getData($sql, $class2);
                        if ($class2['type_id']) {
                                $tc_id = $grp1->addControl("Option", "iaid", getMessage("Input Attribute"), "");

                                $sql = "SELECT
                                DISTINCT ca.id, t.`text`
                                FROM class_attr as ca
                                INNER JOIN attr as a ON (ca.attr_id = a.id)
                                INNER JOIN term as t ON (t.id = a.term_id)
                                WHERE ca.class_id = ".$ID[1]." AND a.`type` = 1";
                                $size = getMultData($sql, $attrList);

                                $sql = "SELECT child_id FROM hierarchy_attr WHERE hierarchy_id = ".$cardinality['id'];
                                getData($sql, $ha);

                                for ($i = 0; $i < $size; $i++) {
                                        $grp1->addOption($attrList[$i]['id'], $attrList[$i]['text'], ($ha['child_id'] == $attrList[$i]['id'] ? "selected" : ""), $tc_id);
                                }
                                $hcid = $grp1->getControl($tc_id);
                        }
                }


      $udata = str_replace($datmatches[0], $classlb.$iclasslb.$utype.$cardinmin.$cardinmax.$constr_name.$hcid.$ubutn.$iparclasslb.$ichiclasslb, $matches[1]);
      $udata = str_replace("%GROUP_ID%", "0", $udata);
      $udata = str_replace("%GROUP_TL%", getMessage("Hierarchy Relationsip"), $udata);
    }else{
      if (getMultData("SELECT * FROM hierarchy WHERE child_class_id =".$ID[0]." and parent_class_id = ".$ID[1], $test_hierarchy) == 1){
        getData("SELECT t.text FROM term t, hierarchy h "."WHERE h.reverse_constr_name = t.id and t.lang_id = ".$language["content"]." and ((h.parent_class_id = ".$ID[0]." and h.child_class_id = ".$ID[1].") or (h.child_class_id = ".$ID[0]." and h.parent_class_id = ".$ID[1]."))", $constr_info);
        $constr_name = str_replace($optmatches[0], "", $datmatches[1]);
        $constr_name = str_replace("%TYPE%", "Label", $constr_name);
        $constr_name = str_replace("%NODE_ID%", "oconstrname", $constr_name);
        $constr_name = str_replace("%NODE_TL%", getMessage("Relationship Name"), $constr_name);
        $constr_name = str_replace("%VALUE%", $constr_info["text"], $constr_name);

        $udata = str_replace($datmatches[0], $classlb.$iclasslb.$constr_name.$hcid, $matches[1]);
        $udata = str_replace("%GROUP_ID%", "0", $udata);
        $udata = str_replace("%GROUP_TL%", getMessage("Reverse Hierarchy Relationsip"), $udata);
      }else{

              $sql = "SELECT o.type_id FROM class as c INNER JOIN ontology as o ON (o.id = c.base_onto_id) WHERE c.id = ".$ID[0];
                getData($sql, $class);
                $hcid = "";
                include "controls.php";

                $grp1 = new ControlGroup(1, getMessage("Input Attribute"), $matches[1], $datmatches, $optmatches);
                $tc_id = $grp1->addControl("Hidden", "iaid", "", "0");
                $hcid = $grp1->getControl($tc_id);

                if ($class['type_id'] == 2 && $ID[1] > 0) {

                        $sql = "SELECT o.type_id FROM class as c INNER JOIN ontology as o ON (o.id = c.base_onto_id) WHERE c.id = ".$ID[1];
                        getData($sql, $class2);
                        if ($class2['type_id']) {
                                $tc_id = $grp1->addControl("Option", "iaid", getMessage("Input Attribute"), htmlspecialchars($WS['func']));

                                $sql = "SELECT
                                ca.id, t.`text`
                                FROM class_attr as ca
                                INNER JOIN attr as a ON (ca.attr_id = a.id)
                                INNER JOIN term as t ON (t.id = a.term_id)
                                WHERE ca.class_id = ".$ID[1]." AND a.`type` = 1";
                                $size = getMultData($sql, $attrList);

                                $sql = "SELECT child_id FROM hierarchy_attr WHERE hierarchy_id = ".$cardinality['id'];
                                getData($sql, $ha);

                                for ($i = 0; $i < $size; $i++) {
                                        $grp1->addOption($attrList[$i]['id'], $attrList[$i]['text'], ($ha['child_id'] == $attrList[$i]['id']), $tc_id);
                                }
                                $hcid = $grp1->getResult();
                        }
                }

        $udata = str_replace($datmatches[0], $classlb.$iclasslb.$hcid, $matches[1]);
        $udata = str_replace("%GROUP_ID%", "0", $udata);
        $udata = str_replace("%GROUP_TL%", getMessage("Hierarchy Relationsip"), $udata);
      };
    };

    //Action
    $btn1 = str_replace($optmatches[0], "", $datmatches[1]);
    $btn1 = str_replace("%TYPE%", "Button", $btn1);
    $btn1 = str_replace("%NODE_ID%", "", $btn1);
    $btn1 = str_replace("%NODE_TL%", getMessage("Ontologies"), $btn1);
    $btn1 = str_replace("%VALUE%", "'wd_tree', 'index.php?trg=ontoedit&amp;sid=".
     $session_id."&amp;act=ontolist&amp;sel=".$onto_name["id"]."'", $btn1);

    $btns = str_replace($datmatches[0], $btn1, $matches[1]);
    $btns = str_replace("%GROUP_ID%", "1", $btns);
    $btns = str_replace("%GROUP_TL%", getMessage("Action"), $btns);
  }
  else { //guest
    //New name
    $contents = str_replace("%NAME%", $ontodata["name"], $contents);
    //Name
    $fname = str_replace($optmatches[0], "", $datmatches[1]);
    $fname = str_replace("%TYPE%", "Label", $fname);
    $fname = str_replace("%NODE_ID%", "oname", $fname);
    $fname = str_replace("%NODE_TL%", getMessage("Name"), $fname);
    $fname = str_replace("%VALUE%", $ontodata["name"], $fname);
    //Description
    $lname = str_replace($optmatches[0], "", $datmatches[1]);
    $lname = str_replace("%TYPE%", "Label", $lname);
    $lname = str_replace("%NODE_ID%", "odescr", $lname);
    $lname = str_replace("%NODE_TL%", getMessage("Description"), $lname);
    $lname = str_replace("%VALUE%", $ontodata["description"], $lname);
    //User
    $udata = str_replace($datmatches[0], $fname.$lname, $matches[1]);
    $udata = str_replace("%GROUP_ID%", "0", $udata);
    $udata = str_replace("%GROUP_TL%", getMessage("Attribute data"), $udata);
    //print "****".$udata."****";
  }

  header ($header["xml"]);
  return str_replace($matches[0], $udata.$btns, $contents);
}


function get_h_inherited($class_id, &$inh_h, &$count){
  $i_max = getMultData("SELECT * FROM hierarchy WHERE parent_class_id=".$class_id, $data);
  for ($i = 0; $i < $i_max; $i++){
    $inh_h[$count] = $data[$i]["child_class_id"];
    $count++;
  };

  $i_max = getMultData("SELECT * FROM hierarchy WHERE child_class_id=".$class_id, $data);
  for ($i = 0; $i < $i_max; $i++){
    $inh_h[$count] = $data[$i]["parent_class_id"];
    $count++;
  };

  getData("SELECT parent_id FROM class WHERE id=".$class_id, $parentdata);
  getData("SELECT * FROM class c, term t WHERE t.id=c.term_id and c.id=".$parentdata["parent_id"], $parentdata1);
  if ($parentdata1["text"] != "Thing")
    get_h_inherited($parentdata["parent_id"], $inh_h, $count);
};

function hierarchy_child($class_id, &$child_h, &$count){
  $i_max = getMultData("SELECT * FROM hierarchy WHERE parent_class_id=".$class_id, $data);
  for ($i = 0; $i < $i_max; $i++){
    $child_h[$count]["id"] = $data[$i]["child_class_id"];
    $child_h[$count]["class_id"] = $data[$i]["parent_class_id"];
    $count++;
  };

  $i_max = getMultData("SELECT * FROM hierarchy WHERE child_class_id=".$class_id, $data);
  for ($i = 0; $i < $i_max; $i++){
    $child_h[$count]["id"] = $data[$i]["parent_class_id"];
    $child_h[$count]["class_id"] = $data[$i]["child_class_id"];
    $count++;
  };

  $i_max = getMultData("SELECT id FROM class WHERE parent_id=".$class_id, $childdata);
  for ($i = 0; $i < $i_max; $i++)
    hierarchy_child($childdata[$i]["id"], $child_h, $count);
};


function createHierarchy() {
  global $_GET, $data, $path, $style, $session_id, $language, $header;
  if (strrpos(substr($_GET["uid"], 1), "h")==false)
    $_GET["uid"] = substr($_GET["uid"], 1);
  else
    $_GET["uid"] = substr($_GET["uid"], 1, strrpos($_GET["uid"], "h") - 1);

  if ($data["type"] >= 1) { //user
      $filename = $path[$style]["tpl"]."/action.xml";
      $fp = fopen($filename, "r");
      $contents = fread($fp, filesize ($filename));
      fclose ($fp);
      preg_match("/\%REPEAT\%(.*?)\%REPEAT\%/s", $contents, $matches);

      $sql_tmp = "SELECT type_id FROM ontology WHERE id = (SELECT onto_id FROM class WHERE id = ".$_GET["uid"].")";
      $ontotype = Array();
      getData($sql_tmp, $ontotype);
      if (!($ontotype["type_id"] == "5")){
        if (getdata("SELECT * FROM hierarchy WHERE parent_class_id=".$_GET["uid"]." and child_class_id=-1", $data) != 1){

          if (getData("SELECT onto_id FROM class where id = ".$_GET["uid"].";", $odatatmp) != 1) return "";
          insertRecord("INSERT INTO hierarchy (onto_id, parent_class_id, child_class_id, session_id) VALUES(".
            $odatatmp["onto_id"].", ".$_GET["uid"].", -1, '".
            $session_id."');");

          if (getData("SELECT id FROM hierarchy where session_id = '".
            $session_id."';", $datatmp) == 1) {
            $sql_str = "UPDATE hierarchy SET session_id = '' WHERE id=".
            $datatmp["id"].";";
            insertRecord($sql_str);
            $contents = str_replace("%SCCSS%", "1", $contents);
            $childs[0]["id"] = -1;
          } else {
            $childs[0]["id"] = "0";
            $contents = str_replace("%SCCSS%", "0", $contents);
            $datatmp["id"] = 0;
          }
        }else{
          $childs[0]["id"] = "0";
          $contents = str_replace("%SCCSS%", "0", $contents);
          $datatmp["id"] = 0;
        };
      }else{
        $childs[0]["id"] = "0";
        $contents = str_replace("%SCCSS%", "0", $contents);
        $datatmp["id"] = 0;
      };
  } else {
    $childs[0]["id"] = "0";
    $contents = str_replace("%SCCSS%", "0", $contents);
    $datatmp["id"] = 0;
  }

  $tmp_cont = str_replace("%NODE_ID%", "h".$_GET["uid"]."h".$childs[0]["id"], $matches[1]);
  $tmp_cont = str_replace("%NODE_NM%", getMessage("Name"), $tmp_cont);
  $tmp_cont = str_replace("%IMG_TYPE%", "class", $tmp_cont);
  $tmp_cont = str_replace("%NODE_LN%", "index.php?trg=ontoedit&amp;act=hierarhydata&amp;sid=".
    $session_id."&amp;uid=com".$childs[0]["id"], $tmp_cont);
  $contents = str_replace($matches[0], $tmp_cont, $contents);
  $contents = str_replace("%XMLSRC%", "index.php?trg=ontoedit&amp;act=hierarchylist&amp;sid=".
    $session_id."&amp;uid=h".$_GET["uid"]."&amp;sel=h".$_GET["uid"]."h".$childs[0]["id"], $contents);
  $contents = str_replace("%ACT_ID%", "Add", $contents);
  $contents = str_replace("%PARENT%", "h".$_GET["uid"], $contents);
  //$contents = str_replace("%SELECT%", "h".$_GET["uid"]."h-1", $contents);

  header ($header["xml"]);
  return $contents;
}

function deleteHierarchy($ID) {
  global $data, $path, $style, $session_id, $header;

  $filename = $path[$style]["tpl"]."/action.xml";
  $fp = fopen($filename, "r");
  $contents = fread($fp, filesize ($filename));
  fclose ($fp);

  preg_match("/\%REPEAT\%(.*?)\%REPEAT\%/s", $contents, $matches);

  $sql_tmp = "SELECT type_id FROM ontology WHERE id = (SELECT onto_id FROM class WHERE id = ".$ID[0].")";
  $ontotype = Array();
  getData($sql_tmp, $ontotype);
  if (!($ontotype["type_id"] == "5")){
    if (isset($ID[1])){
      $count = 0; $inh_h = Array();
      getData("SELECT parent_id FROM class WHERE id=".$ID[0], $parentdata);
      getData("SELECT * FROM class c, term t WHERE t.id=c.term_id and c.id=".$parentdata["parent_id"], $parentdata1);
      if ($parentdata1["text"] != "Thing")
        get_h_inherited($parentdata["parent_id"], $inh_h, $count);
      $b = true;
      for ($i = 0; $i < count($inh_h); $i++)
        if ($inh_h[$i] == $ID[1])
          $b = false;
    };


    if (($data["type"] >= 1 && isset($ID[1]))&&($b)){
        //Delete compatible
        $childs_com = Array(); $count = 0; $k = 0;
        com_child($ID[0], $childs_com, $count);
        for ($j = 0; $j < count($childs_com); $j++)
          if ($ID[1] == $childs_com[$j]["id"])
            insertRecord("DELETE FROM compatible WHERE (class1_id=".$childs_com[$j]["id"]." and class2_id=".$childs_com[$j]["class_id"].") or (class1_id=".$childs_com[$j]["class_id"]." and class2_id=".$childs_com[$j]["id"].");");

        insertRecord("DELETE FROM hierarchy WHERE parent_class_id=".$ID[0]." and child_class_id=".$ID[1]);
        $contents = str_replace("%SCCSS%", "1", $contents);
    }
    else {
      $contents = str_replace("%SCCSS%", "0", $contents);
      $ID[1] = 0;
    }
  }else{
    $contents = str_replace("%SCCSS%", "0", $contents);
    $ID[1] = 0;
  }
  $contents = str_replace($matches[0], "", $contents);
  $contents = str_replace("%ACT_ID%", "Delete", $contents);
  $contents = str_replace("%PARENT%", "h".$ID[0]."h".$ID[1], $contents);
  $contents = str_replace("%SELECT%", "h".$ID[0], $contents);
  header ($header["xml"]);
  return $contents;
}

function updateHierarchy() {
  global $_GET, $data, $path, $style, $session_id, $term_Thing_ID, $language, $header;
  $comment = "";
  if (isset($_GET["otype"]) && $data["type"] >= 1)
    $_GET["otype"] = utf8Encode($_GET["otype"]);
  else
    $_GET["otype"] = -1;
  if (isset($_GET["ohidd"])){
    $_GET["ohidd"] = utf8Encode($_GET["ohidd"]);
    $_GET["ohidd2"] = utf8Encode($_GET["ohidd2"]);
  };
  if (isset($_GET["ocardmin"])) {
    $_GET["ocardmin"] = utf8Encode($_GET["ocardmin"]);
    $_GET["ocardmax"] = utf8Encode($_GET["ocardmax"]);
    if ($_GET["ocardmin"] <= $_GET["ocardmax"] && $_GET["ocardmin"] <> "" && $_GET["ocardmax"] <> ""){
      $sql_str = "UPDATE hierarchy SET card_min = ".$_GET["ocardmin"].", card_max = ".$_GET["ocardmax"].
        " WHERE parent_class_id=".$_GET["ohidd"]." and child_class_id=".$_GET["ohidd2"];
      insertRecord($sql_str);
    }else{
      $_GET["ocardmin"] = -1;
      $_GET["ocardmax"] = -1;
    };
  };

  if (isset($_GET["oconstrname"])) {
    $_GET["oconstrname"] = utf8Encode($_GET["oconstrname"]);
    $sql_str = "INSERT INTO term (lang_id, text, stem_text) VALUES (".$language["content"].", '".$_GET["oconstrname"]."', '".$_GET["oconstrname"]."')";
    insertRecord($sql_str);
    $term_id = GetPreviousInsertedID();

    $sql_str = "UPDATE hierarchy SET constr_name = '".$term_id."' WHERE parent_class_id=".$_GET["ohidd"]." and child_class_id=".$_GET["ohidd2"];
    insertRecord($sql_str);
  };

  $ohidd = $_GET['ohidd'];
  $ohidd2 = $_GET['ohidd2'];

  if (isset($_GET["otype"])&& $_GET["otype"] > -1 && $data["type"] >= 1) {

    $sql_str = "UPDATE hierarchy SET child_class_id = ".$_GET["otype"].
      " WHERE parent_class_id=".$_GET["ohidd"]." and child_class_id=".$_GET["ohidd2"];
    insertRecord($sql_str);
    $ohidd2 = $_GET["otype"];
  }
  header ($header["xml"]);

  if ($_GET['iaid']) {
          $sql = "SELECT id FROM hierarchy WHERE child_class_id = ".$ohidd2." AND parent_class_id=".$ohidd;
          getData($sql, $hierarchy);
          if ($hierarchy['id']) {
                  $sql = "REPLACE hierarchy_attr SET child_id = ".intval($_GET['iaid']).", hierarchy_id = ".$hierarchy['id'];
                  insertRecord($sql);
          }
  }

  $contents = HierarchyData($_GET["otype"], $_GET["ocardmin"], $_GET["ocardmax"]);
  return $contents;
}

?>